#version 330 core
out vec4 result;

in vec2 v_uv;
in vec3 v_position;
in vec3 v_normal;
uniform sampler2D texture_sampler;

// 材质
struct Material{
    vec3 diffuse;  // 控制材质的整体色系.
    vec3 specular;
    float specularPower;
    int hasTexture;
};

// 平行光
struct DirLight{
    vec3 color;
    vec3 dir;
    float intensity;
};

// 一个全局的环境光
uniform vec3 ambient;

uniform Material material;
uniform DirLight dirLight;
uniform vec3 cameraPos; // 相机的位置

//---------------------
// 临时变量
vec3 diffuseC;
vec3 specularC;

// 有纹理就应用纹理
void setupColors(Material material,vec2 texCoord){
    specularC = material.specular;
    if(material.hasTexture == 1){
        diffuseC = material.diffuse * texture(texture_sampler, texCoord).xyz;
    }else{
        diffuseC = material.diffuse;
    }
}

vec3 calcLightColor(vec3 to_light_dir)
{
    vec3 diffuseColour = vec3(0, 0, 0);
    vec3 specColour = vec3(0, 0, 0);

    // Diffuse Light
    float diffuseFactor = max(dot(normal, to_light_dir), 0.0);
    diffuseColour = diffuseC * dirLight.color * dirLight.intensity * diffuseFactor;

    // Specular Light
    vec3 point_to_camera = normalize(cameraPos - position);
    vec3 halfdir = normalize((point_to_camera + to_light_dir) * 0.5f);
    float specularFactor = max(dot(normal,halfdir),0.0);
    specularFactor = pow(specularFactor,material.specularPower);
    specColour = speculrC * dirLight.intensity  * specularFactor  * dirLight.color;

    return diffuseColour + specColour;
}

void main()
{
    setupColors(material,v_uv);
    vec3 color = calcLightColor(dirLight.dir);
    result = vec4(ambient + diffuseC + specularC,1.0);    
} 